package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
@EnableFeignClients(basePackages = "com.leyou.auth.client")
@EnableConfigurationProperties(ClientProperties.class)
@ConditionalOnProperty(prefix = "ly.auth",name = {"clientId","secret"})//条件限制，当微服务配置文件中有这两个属性时，当前配置才会生效，才去申请密钥，否则不申请
public class AuthConfiguration {

    @Autowired
    private AuthClient authClient;

    @Bean
    public JwtUtils jwtUtils(ClientProperties prop) throws InterruptedException {
        while (true){
            try {
                //各个微服务向ly-auth申请密钥
                String key = authClient.getSecretKey(prop.getClientId(), prop.getSecret());
                log.info("==============获取密钥成功！================");
                //创建JwtUtils对象
                return new JwtUtils(key);
            } catch (Exception e) {
                log.error("申请jwt密钥失败，原因：{}，会在10秒后重试，",e.getMessage());
                Thread.sleep(10000);
            }
        }
    }
}
